<template>
	<view class="loginMain">
		<u-navbar back-icon-color="#fff" title-color="#fff" title="短信验证码登录" :background="navBackground" :border-bottom="false">
			
		</u-navbar>
		<view class="tac">
			<image src="../../static/logo.png" style="width: 200rpx;height: 200rpx;" mode=""></image>
			<view class="cf fs30 fwb">宅美批发商城</view>
		</view>

		<view class="bgcf bdr20 p30 mt60">
			<u-form class="" :model="form" ref="uForm">
				<u-form-item class="mobileItem" prop="mobile" :left-icon-style="{
					width:'24rpx',
					height:'30rpx'}"
					left-icon="https://zhaimeibianli.oss-cn-hangzhou.aliyuncs.com/house/2023/12/06/d13bb20bbaec44d88aff9131640de173.png">
					<u-input type="number" :custom-style="customStyle" placeholder-style="color:#999"
						v-model="form.mobile" placeholder="请输入您的手机号码" />
				</u-form-item>
				<u-form-item class="codeItem mt30" prop="code" :left-icon-style="{
					width:'28rpx',
					height:'35rpx'}"
					left-icon="https://zhaimeibianli.oss-cn-hangzhou.aliyuncs.com/house/2023/12/06/d312d27ca829429d8c44c13cf2a53a25.png">
					<u-input :custom-style="customStyle" placeholder-style="color:#999" type="number"
						placeholder="请输入验证码" v-model="form.code" />
					<view class="" slot="right">
						<u-toast ref="uToast"></u-toast>
						<u-verification-code :seconds="seconds" end-text="获取验证码" @end="end" @start="start" ref="uCode"
							@change="codeChange"></u-verification-code>
						<u-button :hair-line="false" :ripple="true" hover-class="none" shape="circle" :plain="true"
							:custom-style="customBtnStyle" @click="getCode">{{tips}}</u-button>
					</view>
				</u-form-item>
				<view class="aic df  fs26 mt30">
					<u-checkbox-group size="30" class="checkboxGroup mr16">
						<u-checkbox shape="circle" v-model="checked" active-color="#48A147"></u-checkbox>
					</u-checkbox-group>
					<text class="c9">我已阅读并同意</text>
					<text style="color: #48A147;" @click="itemClick(2)">《隐私政策》</text>
				</view>
				<view class="mt40">
					<u-button  ripple type="primary" :custom-style="{
					background:'linear-gradient(90deg, #48A147 0%, #8AE38A 100%)',
					height:'88rpx',
					color:'#fff',
					opacity:checked ? 1 : 0.6
				}" :disabled="!checked" class="" shape="circle" @click="submit" >登录</u-button>

					<view class="mt40">
						<u-button ripple :custom-style="{
							background:'#fff',
							border:'2rpx solid #48A147',
							color:'#48A147',
							height:'88rpx'
						}"  shape="circle" :hair-line="false" @click="backNext">返回手机号快捷登录</u-button>
					</view>
				</view>
			</u-form>

		</view>
	</view>
</template>

<script>
	import {
		signInJump
	} from "@/utils/login.js";
	import {
		registerLoginByPhone,
		captchaSms,
		getInfo,
		code2Session
	} from '@/api/login.js'
	import {
		getDefaultAddress
	} from '@/api/address.js'
	export default {
		data() {
			return {
				code: '',
				openId: '',
				token: '',
				sessionId: '',
				userInfo: {},
				navBackground:{
					background: 'transparent'
				},
				checked: false,
				customBtnStyle: {
                    // width:'150rpx',
					// height:'48rpx',
					// background: '#fff',
					color: '#48A147',
					// fontSize:'24rpx',
					border: 'none'
				},
				tips: '获取验证码',
				// refCode: null,
				seconds: 60,
				form: {
					mobile: '',
					code: ''
				},
				customStyle: {},
				rules: {
					// 字段名称
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],

						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// this.$u.test.mobile()就是返回true或者false的
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					code: [
						// 对name字段进行长度验证
						{
							min: 6,
							message: '验证码为数字且不能少于6位数',
							trigger: 'change',
							type: 'number'
						},
						// 对name字段进行必填验证
						{
							required: true,
							message: '请填写验证码',
							trigger: ['change', 'blur'],
							type: 'number'
						},
					]
				}
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad() {
			this.$u.vuex('TOKEN', '')
		},
		onShow() {
			this.login()
		},
		methods: {
			login() {
				let that = this
				uni.login({
					provider: "weixin",
					success: (loginRes) => {
						if (loginRes.errMsg === "login:ok") {
							that.code = loginRes.code;
						}
					},
					fail: (res) => {},
				});
				uni.getUserInfo({
					desc: "小程序登录",
					success: async (res) => {
						that.userInfo = res.userInfo
						await that.code2Session()
					},
					fail: (e) => {
					},
				});
			},
			code2Session() {
				return code2Session({
					jsCode: this.code
				}).then(e => {
					if (e.code === 200) {
						this.openId = e.data.openid
						this.sessionId = e.data.sessionId
						uni.setStorageSync('openid', e.data.openid)
						this.unionid = e.data.unionid
					}
				})
			},
			backNext(){
				console.log('00000')
				uni.navigateBack()
			},
			itemClick() {
				wx.openPrivacyContract({
					success: () => {}, // 打开成功
					fail: () => {}, // 打开失败
					complete: () => {}
				})
			},
			submit() {
				this.$refs.uForm.validate(valid => {
					
					if (valid) {
							 registerLoginByPhone({
								isWxPhone: false,
								phone: this.form.mobile,
								nickname: this.userInfo.nickName,
								headPhoto: this.userInfo.avatarUrl,
								openId: this.openId,
								unionid: this.unionid,
								uuid: this.uuid,
								smsCode: this.form.code,
							}).then(res => {
								if (res.code === 200) {
									this.$u.vuex('_newUSerCoupon', {
										isNewMemberCoupon: res.data.isNewMemberCoupon,
										memberCouponMoney: res.data.memberCouponMoney || 0
									})
									this.$u.vuex('TOKEN', res.data.token)
									uni.setStorageSync('token', res.data.token)
									getInfo().then(res => {
										this.$u.vuex('USERINFO', res.data)
										this.getDefault()
									})
								} else {
									this.$u.toast(res.msg)
								}
						
							})
					} else {
						console.log('验证失败');
					}
				});
			},
			getDefaultAddress() {
				getDefaultAddress().then(res => {
					if (res.code == 200) {
						uni.redirectTo({
							url: '/pages/addressLocation'
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							mask: true
						})
					}
				})
			},
			getDefault() {
				if (!this.LOCATION.name) { //缓存中有地址
					this.getDefaultAddress()
				}else{
					signInJump()
				}
			},

			codeChange(text) {
				this.tips = text;
			},

			getCode() {
				if(!this.$u.test.mobile(this.form.mobile)){
					this.$u.toast('请输入正确手机号')
					return
				}
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					captchaSms({
						phonenumber: this.form.mobile
					}).then(res => {
						if (res.code == 200) {
							this.$u.toast('验证码已发送');
							// 通知验证码组件内部开始倒计时
							this.$refs.uCode.start();
						}
						uni.hideLoading()
					})
				} else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
			end() {
				// this.$u.toast('倒计时结束');
			},
			start() {
				// this.$u.toast('倒计时开始');
			}
		}
	}
</script>

<style scoped lang="scss">
	.mobileItem ::v-deep .u-form-item--left__content__icon {
		height: 50rpx !important;
	}

	.mobileItem ::v-deep .u-form-item__message {
		padding-left: 44rpx !important;
	}

	.codeItem ::v-deep .u-form-item__message {
		padding-left: 44rpx !important;
	}

	.checkboxGroup ::v-deep .u-checkbox {
		display: inline-block
	}

	.codeItem ::v-deep .u-form-item--left__content__icon {
		height: 65rpx !important;
	}

	.loginMain {
		box-sizing: border-box;
		height: 100%;
		width: 100%;
		background-image: url('https://zhaimeibianli.oss-cn-hangzhou.aliyuncs.com/house/2023/12/06/4319381196fc4d008e57b60358ffe013.png');
		background-size: 100%;
		padding: 30rpx;
		padding-top: 200rpx;
	}
</style>